import os
import multiprocessing
import click
import platform


@click.command()
def build_deploy_scheme():
    sys = platform.system()
    if sys != 'Linux':
        exit("Environments other than Linux are not supported")
    Build.run()


class Build:
    def __init__(self):
        self.path = os.getcwd().replace('\\', '/')
        self.web_name = 'website_{}'.format(self.path[self.path.rindex('/') + 1:])
        self.unix = 'unix:/tmp/{}.sock'.format(self.web_name)
        self.deploy_path = os.path.join(self.path, 'deploy')
        self.gunicorn_path = os.path.join(self.deploy_path, 'gunicorn.py')
        self.service_path = os.path.join(self.deploy_path, '{}.service'.format(self.web_name))
        self.nginx_path = os.path.join(self.deploy_path, '{}.conf'.format(self.web_name))

    @classmethod
    def run(cls):
        obj = cls()
        if not os.path.exists(obj.deploy_path):
            click.echo('Build Deploy Start...')
            os.mkdir(obj.deploy_path)
            obj.gunicorn()
            obj.service()
            obj.nginx()
            click.echo('Success Deploy')
            logs = os.path.join(obj.path, 'logs')
            if not os.path.exists(logs):
                os.mkdir(logs)
        else:
            click.echo('Already Deployed Builds')
        return obj

    def gunicorn(self):
        gunicorn_content = """bind = '{bind}'
workers = {workers}
loglevel = '{loglevel}'
errorlog = './logs/error.log'
accesslog = './logs/access.log'
"""
        click.echo('build gunicorn.conf...')
        with open(self.gunicorn_path, 'w') as f:
            workers = multiprocessing.cpu_count() * 2
            loglevel = 'debug'
            f.write(gunicorn_content.format(
                bind=self.unix,
                workers=workers,
                loglevel=loglevel
            ))

    def service(self):
        service_content = """[Unit]
Description={description}
After=network.target

[Service]
WorkingDirectory={working_directory}
ExecStart={exec_start}
Restart=on-failure

[Install]
WanteBy=multi-user.target
"""
        click.echo('build systemd service...')
        with open(self.service_path, 'w') as f:
            description = 'website application of {}'.format(self.web_name)
            working_directory = self.path
            exec_start = '{} -c deploy/gunicorn.py wsgi:application'.format(
                os.path.join(self.path, 'venv', 'bin', 'gunicorn').replace('\\', '/')
            )
            f.write(service_content.format(
                description=description,
                working_directory=working_directory,
                exec_start=exec_start
            ))

    def nginx(self):
        nginx_content = """server {
    listen 80;
    server_name *;
    location / {
        proxy_pass http://%s;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    location /static {
        alias %s;
        expires 30d;
    }
}
"""
        click.echo('build nginx config file')
        with open(self.nginx_path, 'w') as f:
            f.write(nginx_content % (
                self.unix,
                os.path.join(self.path, 'public', 'static').replace('\\', '/')
            ))

    def transfer_service(self):
        if not os.path.exists('/usr/lib/systemd/system/{}.service'.format(self.web_name)):
            click.echo('add of service to systemctl')
            os.system("sudo cp {} /usr/lib/systemd/system/{}.service".format(
                self.service_path,
                self.web_name
            ))

    def transfer_nginx(self):
        pass
